package com.three.crm.page.goods;


import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.three.crm.R;
import com.three.crm.adapter.NinePictureAdapter;
import com.three.crm.alioos.AliyunOSSUploadHelper;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CommonBean;
import com.three.crm.bean.CompanyBean;
import com.three.crm.bean.CosTokenBean;
import com.three.crm.bean.FileBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.page.VideoPlayActivity;
import com.three.crm.page.company.CompanyActivity;
import com.three.crm.page.procure.OrderListActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.tencentcloud.BaseConfig;
import com.three.crm.tencentcloud.CosServiceFactory;
import com.three.crm.tencentcloud.CosServiceUtils;
import com.three.crm.util.AppManager;
import com.three.crm.util.GlideEngine;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.PercentUtil;
import com.three.crm.util.PictureSelectorUtil;
import com.three.crm.util.SignUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 货物登记
 * created by lqd on 2024-01-06.
 */
public class GoodsEditActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks{

    private TextView tvTitle,tvCarTime,tvGoodsUnit,tvFeeType;
    private EditText etCarInfo,etCarDriver,etRemark,etGoodsWeight,etPrice,etTotal,etYunfei,etDriverCard,etDriverPhone;
    private ImageView ivVideo;
    private FrameLayout flVideo;

    public final static String[] PERMISSES = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
    };
    private boolean hasPermiss = false;
    private RecyclerView rvPicture,rvPictureOrder;
    private NinePictureAdapter ninePictureAdapter,orderNinePictureAdapter;
    private int maxSelectPicture = 9;
    private List<FileBean> pictureList = new ArrayList<>();
    private List<FileBean> orderPictureList = new ArrayList<>();

    private TransferManager transferManager;
    private CosServiceUtils serviceUtils;
    private AliyunOSSUploadHelper uploadHelper = null;
    private String uploadVideoPath = "",carTime = "";

    private int companyId = 0;
    private int detailId = 0;
    private CommonBean bean = null;

    private int orderId = 0,xpopupUnitPos = 0,xpopupFeePos = 1;
    private LinearLayout llOrder;
    private TextView tvOrderName,tvGoodsName,tvGoodsNum;
    //日期对话框
    private DatePickerDialog datePickerDialog;
    private int curYear, monthOfYear, dayOfMonth;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher,resultLaunchOrder;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            switch (msg.what){
                case AppConstant.UPLOAD_PROGRESS:
                    long completeCover = bundle.getLong("complete");
                    long targetCover = bundle.getLong("target");
                    showLoading(getString(R.string.progress) + PercentUtil.getPercent(completeCover,targetCover) + "%");
                    break;
                case AppConstant.UPLOAD_COMPLETED:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    break;
                case AppConstant.UPLOAD_IMAGE_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    String tempUrl = bundle.getString(AppConstant.IMAGE_PATH);
                    Log.i("TAG","tempUrl="+tempUrl);
                    handleImg(tempUrl);
                    break;
                case AppConstant.UPLOAD_FAIL:
                    hideLoading();
                   // showToast(getString(R.string.upload_fail));
                    break;
                case AppConstant.UPLOAD_VIDEO_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    uploadVideoPath = bundle.getString(AppConstant.VIDEO_PATH);
                    handleVideo();
                    break;
                case AppConstant.UPLOAD_COVER_SUCCESS:
                    hideLoading();
                    showToast(getString(R.string.upload_success));
                    String tempUrl2 = bundle.getString(AppConstant.COVER_PATH);
                    Log.i("TAG","tempUrl="+tempUrl2);
                    handleOrderImg(tempUrl2);
                    break;
            }
        }
    };

    private void handleImg(String tempUrl) {
        FileBean bean = new FileBean();
        bean.setUrl(tempUrl);
        pictureList.add(bean);
        ninePictureAdapter.setNewData(pictureList);
    }

    private void handleOrderImg(String tempUrl) {
        FileBean bean = new FileBean();
        bean.setUrl(tempUrl);
        orderPictureList.add(bean);
        orderNinePictureAdapter.setNewData(orderPictureList);
    }

    private void handleVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            flVideo.setVisibility(View.GONE);
        } else {
            flVideo.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(uploadVideoPath)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_default_image)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(ivVideo);
        }
    }

    @Override
    protected void initParms(Bundle bundle) {
        if (bundle != null) {
            bean = bundle.getParcelable(AppConstant.EXTRAS_DATA);
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_goods_edit;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    CompanyBean companyBean = (CompanyBean) result.getData().getExtras().get(AppConstant.EXTRAS_BEAN);
                  //  tvCustomer.setText(companyBean.getTitle());
                   // companyId = companyBean.getId();
                }
            }
        });
        resultLaunchOrder = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    CommonBean commonBean = (CommonBean) result.getData().getExtras().get(AppConstant.EXTRAS_BEAN);
                    if (commonBean != null) {
                        orderId = commonBean.getId();
                        llOrder.setVisibility(View.VISIBLE);
                        tvOrderName.setText(commonBean.getTitle());
                        tvGoodsName.setText(commonBean.getGoods_name());
                        tvGoodsNum.setText(commonBean.getGoods_num());
                        tvGoodsUnit.setText(commonBean.getGoods_unit());

                        //onCalculatePrice();
                    }
                }
            }
        });

        //初始化日历
        Calendar calendar = Calendar.getInstance();
        curYear = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        onCheckPermission();
        tvTitle = $(R.id.tv_title);
        tvTitle.setText(R.string.form_add);

        etRemark = $(R.id.et_remark);
        etGoodsWeight = $(R.id.et_weight);
        tvGoodsUnit = $(R.id.tv_unit);
        etPrice = $(R.id.et_price);
        etTotal = $(R.id.et_total);
        tvFeeType = $(R.id.tv_fee_type);
        etYunfei = $(R.id.et_yunfei);


        etCarInfo = $(R.id.et_car_info);
        etCarDriver = $(R.id.et_car_driver);
        etDriverCard = $(R.id.et_driver_card);
        etDriverPhone = $(R.id.et_driver_phone);
        tvCarTime = $(R.id.tv_car_time);

        ivVideo = $(R.id.iv_video);
        flVideo = $(R.id.fl_video);

        llOrder = $(R.id.ll_order);
        tvOrderName = $(R.id.tv_order_name);
        tvGoodsName = $(R.id.tv_goods_name);
        tvGoodsNum = $(R.id.tv_goods_num);
        tvGoodsUnit = $(R.id.tv_goods_unit);

        rvPicture = $(R.id.rv_picture);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        rvPicture.setLayoutManager(layoutManager);
        ninePictureAdapter = new NinePictureAdapter();
        ninePictureAdapter.setType("");
        rvPicture.setAdapter(ninePictureAdapter);

        rvPictureOrder = $(R.id.rv_picture_bg);
        GridLayoutManager layoutManager2 = new GridLayoutManager(this,3);
        rvPictureOrder.setLayoutManager(layoutManager2);
        orderNinePictureAdapter = new NinePictureAdapter();
        orderNinePictureAdapter.setType("");
        rvPictureOrder.setAdapter(orderNinePictureAdapter);

        orderId = bean.getId();
        llOrder.setVisibility(View.VISIBLE);
        tvOrderName.setText(bean.getTitle());
        tvGoodsName.setText(bean.getGoods_name());
        tvGoodsNum.setText(bean.getGoods_num());
        tvGoodsUnit.setText(bean.getGoods_unit());

        int productId = bean.getProduct_upload_id();

        if (productId != 0) {
            etDriverPhone.setText(bean.getDriver_phone());
            etDriverCard.setText(bean.getDriver_idcard());
            tvTitle.setText(R.string.form_edit);
            companyId = bean.getCompany_id();
            detailId = bean.getProduct_upload_id();
            etRemark.setText(bean.getNote());
            etGoodsWeight.setText(bean.getGoods_weight());
            tvGoodsUnit.setText(bean.getGoods_unit());
            etYunfei.setText(bean.getFreight());
            etCarInfo.setText(bean.getCar_info());
            etCarDriver.setText(bean.getCar_driver());
            tvCarTime.setText(bean.getCar_time());
            etPrice.setText(bean.getPrice());
            etTotal.setText(bean.getMoney());
            carTime = bean.getCar_time();
            uploadVideoPath = bean.getVideo_url();
            handleVideo();

            //orderId = bean.getParent_id();
           // orderId = bean.getId();
            llOrder.setVisibility(View.VISIBLE);
            tvOrderName.setText(bean.getTitle());
            tvGoodsName.setText(bean.getGoods_name());
            tvGoodsNum.setText(bean.getGoods_num());
            tvGoodsUnit.setText(bean.getGoods_unit());

            String bdImgArr = bean.getBangdan_images();
            String[] bdimgs = bdImgArr.split(",");
            if (bdimgs != null && bdimgs.length > 0) {
                for (int i = 0; i < bdimgs.length; i++) {
                    String url = bdimgs[i];
                    FileBean bean = new FileBean();
                    bean.setUrl(url);
                    orderPictureList.add(bean);
                }
                orderNinePictureAdapter.setNewData(orderPictureList);
            }

            String[] imgs = bean.getImgs_arr();
            if (imgs != null && imgs.length > 0) {
                for (int i = 0; i < imgs.length; i++) {
                    String url = imgs[i];
                    FileBean bean = new FileBean();
                    bean.setUrl(url);
                    pictureList.add(bean);
                }
                ninePictureAdapter.setNewData(pictureList);
            }
        }
    }

    private void onCalculatePrice() {
        String goodsCount = etGoodsWeight.getText().toString().trim();
        String price = etPrice.getText().toString().trim();
        if (TextUtils.isEmpty(goodsCount) || TextUtils.isEmpty(price)) {
            etTotal.setText("0");
        } else {
            double priceD = Double.parseDouble(price);
            double goodsCountD = Double.parseDouble(goodsCount);
            if (priceD >0 && goodsCountD > 0) {
                double result = priceD * goodsCountD;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");

                etTotal.setText("" + decimalFormat.format(result));
            } else {
                etTotal.setText("0");
            }

        }

    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(this,PERMISSES)){
            hasPermiss = true;
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要使用相机、手机存储、定位等权限，您是否同意?",
                    AppConstant.RC_PERMISSES, PERMISSES);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.fl_video).setOnClickListener(this);
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.btn_submit).setOnClickListener(this);
        $(R.id.iv_take_picture).setOnClickListener(this);
        $(R.id.iv_take_video).setOnClickListener(this);
        $(R.id.ll_car_time).setOnClickListener(this);
        $(R.id.iv_take_picture_bd).setOnClickListener(this);
        $(R.id.iv_add_order).setOnClickListener(this);
        $(R.id.ll_yfjsfs).setOnClickListener(this);
        $(R.id.ll_unit).setOnClickListener(this);
        ninePictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                FileBean bean = (FileBean) baseQuickAdapter.getItem(position);
                String imgUrl = bean.getUrl();
                switch (view.getId()){
                    case R.id.iv_delete:
                        deleteByPath(imgUrl);
                        break;
                }
            }
        });
        orderNinePictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                FileBean bean = (FileBean) baseQuickAdapter.getItem(position);
                String imgUrl = bean.getUrl();
                switch (view.getId()){
                    case R.id.iv_delete:
                        deleteOrderByPath(imgUrl);
                        break;
                }
            }
        });
        etGoodsWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onCalculatePrice();
                handleFee();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onCalculatePrice();
                handleFee();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void deleteOrderByPath(String path) {
        int selectPos = -1;
        for (int i = 0; i < orderPictureList.size(); i++) {
            FileBean bean = orderPictureList.get(i);
            if (path.equals(bean.getUrl())) {
                selectPos = i;
                break;
            }
        }
        orderPictureList.remove(selectPos);
        orderNinePictureAdapter.setNewData(orderPictureList);
    }

    private void deleteByPath(String path){
        int selectPos = -1;
        for (int i = 0; i < pictureList.size(); i++) {
            FileBean bean = pictureList.get(i);
            if (path.equals(bean.getUrl())) {
                selectPos = i;
                break;
            }
        }
        pictureList.remove(selectPos);
        ninePictureAdapter.setNewData(pictureList);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.iv_take_picture:
                if (hasPermiss) {
                    if (pictureList.size() == maxSelectPicture) {
                        showToast("最多只能上传9张图片");
                    } else {
                        onTakePicture();
                    }
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.iv_take_picture_bd:
                if (hasPermiss) {
                    if (orderPictureList.size() == maxSelectPicture) {
                        showToast("最多只能上传9张图片");
                    } else {
                        onTakeOrderPicture();
                    }
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.iv_take_video:
                if (hasPermiss) {
                    onTakeVideo();
                } else {
                    onCheckPermission();
                }
                break;
            case R.id.btn_submit:
                onSubmit();
                break;
//            case R.id.ll_customer:
//                onSelectCompany();
//                break;
            case R.id.fl_video:
                onPlayVideo();
                break;
            case R.id.ll_car_time:
                onSelectTime();
                break;
            case R.id.iv_add_order:
                onSelectOrder();
                break;
            case R.id.ll_unit:
                onSelectUnit();
                break;
            case R.id.ll_yfjsfs:
                onSelectFeeType();
                break;
        }
    }

    private void onSelectFeeType() {
        String[] items = new String[]{"包运费","按吨计算","按车计算"};
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("请选择", items,
                        null, xpopupFeePos,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                xpopupFeePos = position;
                                tvFeeType.setText(text);
                                if (position == 0) {
                                    etYunfei.setText("0");
                                } else if (position == 2) {
                                    etYunfei.setText("");
                                } else if (position == 1){
                                    handleFee();
                                }

                            }
                        })
                .show();
    }

    private void handleFee() {
        String unit = tvGoodsUnit.getText().toString();
        String num = etGoodsWeight.getText().toString();
        String price = etPrice.getText().toString();
        if (TextUtils.isEmpty(num) || TextUtils.isEmpty(price)) {
            etYunfei.setText("");
        } else {
            double priceD = Double.parseDouble(price);
            double goodsCountD = Double.parseDouble(num);
            if (priceD > 0 && goodsCountD > 0) {
                double result = priceD * goodsCountD;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                etYunfei.setText("" + decimalFormat.format(result));
                if (unit.equals("kg")) {
                    etYunfei.setText("" + (1000 * Float.parseFloat(decimalFormat.format(result))));
                }

            } else {
                etYunfei.setText("0");
            }

        }
    }

    private void onSelectUnit() {
        String[] items = new String[]{"吨","kg"};
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("请选择", items,
                        null, xpopupUnitPos,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                xpopupUnitPos = position;
                                tvGoodsUnit.setText(text);
                                handleFee();
                            }
                        })
                .show();
    }

    private void onSelectCompany() {
        Intent intent = new Intent(this, CompanyActivity.class);
        intentActivityResultLauncher.launch(intent);
    }


    private void onSelectOrder() {
        Intent intent = new Intent(this, OrderListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.EXTRAS_DATA,"select");
        intent.putExtras(bundle);
        resultLaunchOrder.launch(intent);
    }

    private void onSelectTime() {
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                String text = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                carTime = text;
                tvCarTime.setText(text);
            }
        }, curYear, monthOfYear, dayOfMonth);
        datePickerDialog.show();
    }

    private void onPlayVideo() {
        if (TextUtils.isEmpty(uploadVideoPath)) {
            showToast("视频不存在了");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.VIDEO_PATH,uploadVideoPath);
        startActivity(VideoPlayActivity.class,bundle);
    }

    private void onTakeVideo() {
        PictureSelector.create(this)
               // .openCamera(SelectMimeType.ofVideo())
                .openGallery(SelectMimeType.ofVideo())
                .setMaxSelectNum(1)
                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
                .setSelectionMode(SelectModeConfig.SINGLE)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        LocalMedia media = result.get(0);
                        uploadFile(media,"video");
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择视频的操作");
                    }
                });
    }

    private void uploadFile(LocalMedia media,String index) {
        showLoading(getString(R.string.uploading));
        int successCode = AppConstant.UPLOAD_IMAGE_SUCCESS;
        String successPath = AppConstant.IMAGE_PATH;
        if (index.equals("video")) {
            successCode = AppConstant.UPLOAD_VIDEO_SUCCESS;
            successPath = AppConstant.VIDEO_PATH;
        } else if (index.equals("order")) {
            successCode = AppConstant.UPLOAD_COVER_SUCCESS;
            successPath = AppConstant.COVER_PATH;
        }
        int finalSuccessCode = successCode;
        String finalSuccessPath = successPath;
        uploadHelper.uploadFile(media.getRealPath(),media.getMimeType(),media.getFileName(), new AliyunOSSUploadHelper.OSSCallback() {
            @Override
            public void onProgress(long complete, long target,String url) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                message.what = AppConstant.UPLOAD_PROGRESS;
                bundle.putLong("complete",complete);
                bundle.putLong("target",target);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onSuccess(String url) {
                Message message = new Message();
                message.what = finalSuccessCode;
                Bundle bundle = new Bundle();
                bundle.putString(finalSuccessPath,url);
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(ClientException clientExcepion, ServiceException serviceException) {
                Message message = new Message();
                message.what = AppConstant.UPLOAD_FAIL;
                handler.sendMessage(message);
            }
        });
    }

    private void onTakeOrderPicture() {
        PictureSelector.create(this)
               // .openCamera(SelectMimeType.ofImage())
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(maxSelectPicture - orderPictureList.size())
                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
                .setSelectionMode(SelectModeConfig.MULTIPLE)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        handleOrderPictureList(result);
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择");
                    }
                });
    }

    private void handleOrderPictureList(ArrayList<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            LocalMedia media = result.get(i);
            uploadFile(media,"order");
        }
    }

    private void onTakePicture() {
        PictureSelector.create(this)
                //.openCamera(SelectMimeType.ofImage())
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(maxSelectPicture - pictureList.size())
                .setSelectorUIStyle(PictureSelectorUtil.getSelectorStyle(this))
                .setSelectionMode(SelectModeConfig.MULTIPLE)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        handlePictureList(result);
                    }

                    @Override
                    public void onCancel() {
                        showToast("您取消了选择");
                    }
                });
    }


    @Override
    protected void initData(Context mContext) {
        initCosToken();
    }

    private void onSubmit() {
        if (orderId == 0) {
            showToast("请选择采购单");
            return;
        }
        String goodsWeight = etGoodsWeight.getText().toString();
        if (TextUtils.isEmpty(goodsWeight)) {
            showToast("请填写过磅重量");
            etGoodsWeight.requestFocus();
            return;
        }
        String goodsUnit = tvGoodsUnit.getText().toString();
        if (TextUtils.isEmpty(goodsUnit)) {
            showToast("请填写货物单位");
            //etGoodsUnit.requestFocus();
            return;
        }
        String goodsPrice = etPrice.getText().toString();
        if (TextUtils.isEmpty(goodsPrice)) {
            showToast("请填写货物单价");
            etPrice.requestFocus();
            return;
        }
        String goodsTotal = etTotal.getText().toString();
        if (TextUtils.isEmpty(goodsTotal)) {
            showToast("请填写货物金额");
            etTotal.requestFocus();
            return;
        }
        String freight = etYunfei.getText().toString();
        if (TextUtils.isEmpty(freight)) {
            showToast("请填写货物运费");
            etYunfei.requestFocus();
            return;
        }
        String carInfo = etCarInfo.getText().toString();
        if (TextUtils.isEmpty(carInfo)) {
            showToast("请填写车辆信息");
            etCarInfo.requestFocus();
            return;
        }
        String carDriver = etCarDriver.getText().toString();
        if (TextUtils.isEmpty(carDriver)) {
            showToast("请填写车辆司机姓名");
            etCarDriver.requestFocus();
            return;
        }
        String driverCard = etDriverCard.getText().toString();
//        if (TextUtils.isEmpty(driverCard)) {
//            showToast("请填写车辆司机");
//            etDriverCard.requestFocus();
//            return;
//        }
        String driverPhone = etDriverPhone.getText().toString();
        if (TextUtils.isEmpty(driverPhone)) {
            showToast("请填写车辆司机电话号码");
            etDriverPhone.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(carTime)) {
            showToast("请选择到货时间");
            return;
        }
        if (pictureList.size() == 0) {
            showToast("请上传货物照片");
            return;
        }
        if (orderPictureList.size() == 0) {
            showToast("请上传磅单照片");
            return;
        }
        String remark = etRemark.getText().toString();
//        if (TextUtils.isEmpty(remark)) {
//            showToast("请填写备注");
//            etRemark.requestFocus();
//            return;
//        }
//        if (TextUtils.isEmpty(uploadVideoPath)) {
//            showToast("请上传货物视频");
//            return;
//        }
        showLoading(getString(R.string.submitting));
        JSONObject jsonObject = new JSONObject();

        String files = "";
        int fileSize = pictureList.size();
        if (fileSize > 0) {
            for (int i = 0; i < fileSize; i++) {
                FileBean bean = pictureList.get(i);
                files += bean.getUrl();
                if (fileSize - 1 != i) {
                    files += ",";
                }
            }
        }

        String bdfiles = "";
        int bdfileSize = orderPictureList.size();
        if (bdfileSize > 0) {
            for (int i = 0; i < bdfileSize; i++) {
                FileBean bean = orderPictureList.get(i);
                bdfiles += bean.getUrl();
                if (bdfileSize - 1 != i) {
                    bdfiles += ",";
                }
            }
        }

        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("company_id",companyId);
            jsonObject.put("parent_id",orderId);
            jsonObject.put("goods_weight",goodsWeight);
            jsonObject.put("goods_unit",goodsUnit);
            jsonObject.put("price",goodsPrice);
            jsonObject.put("money",goodsTotal);
            jsonObject.put("freight_type",xpopupFeePos + 1);
            jsonObject.put("freight",freight);
            jsonObject.put("car_info",carInfo);
            jsonObject.put("car_driver",carDriver);
            jsonObject.put("driver_idcard",driverCard);
            jsonObject.put("driver_phone",driverPhone);
            jsonObject.put("car_time",carTime);
            jsonObject.put("video_url",uploadVideoPath);
            jsonObject.put("bangdan_images",bdfiles);
            jsonObject.put("note",remark);
            jsonObject.put("id",detailId);
            jsonObject.put("images",files);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.addProduce(this,AppConstant.FORM_SUBMIT,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void handlePictureList(ArrayList<LocalMedia> result) {
        for (int i = 0; i < result.size(); i++) {
            LocalMedia localMedia = result.get(i);
            uploadFile(localMedia,"image");
        }
    }

    private void initCosToken() {
        showLoading(getString(R.string.loading));
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.getCosConfig(this,AppConstant.QUERY_TOKEN,jsonObject,callBack);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CommonResultCallBack callBack = new CommonResultCallBack(this) {
        @Override
        public void onResult(String result, int requireCode) {
            Log.i("TAG","result="+result);
            hideLoading();
            if (requireCode == AppConstant.QUERY_TOKEN) {
                if (result != null) {
                    CosTokenBean bean = GsonUtils.parseJsonWithGson(result, CosTokenBean.class);
                    initFileWithCosService(bean);
                }
            } else if (requireCode == AppConstant.FORM_SUBMIT) {
                AppManager.setNeedUpdate(true);
                showToast("操作成功");
                finish();
            }
        }

        @Override
        public void onConnectTimeOut(Call call, Exception e, int requireCode) {
            showToast(e.getMessage());
            hideLoading();
        }

        @Override
        public void onFail(String msg, int requireCode) {
            showToast(msg);
            hideLoading();
        }
    };

    private void initFileWithCosService(CosTokenBean bean) {
//        transferManager = CosServiceFactory.getTransferManager(this, BaseConfig.REGION,BaseConfig.SECRETID,BaseConfig.SECRETKEY,bean.getToken(),bean.getStartTime(),bean.getExpirationAt(),true);
//        serviceUtils = new CosServiceUtils(transferManager);
        uploadHelper = new AliyunOSSUploadHelper(this,bean.getBucket(),bean.getEndpoint(),bean.getAccessKeyId(),bean.getAccessKeySecret(),bean.getSecurityToken());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {
        showToast("好伤心，您将无法使用定位等相关功能");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
    }
}